<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
                 label-width="68px">
            <el-form-item label="编号" prop="name">
                <el-input v-model="queryParams.no" placeholder="请输入名称" clearable
                          @keyup.enter.native="handleQuery"/>
            </el-form-item>
            <el-form-item label="耗材名称" prop="name">
                <el-input v-model="queryParams.name" placeholder="请输入名称" clearable
                          @keyup.enter.native="handleQuery"/>
            </el-form-item>

            <el-form-item label="型号" prop="model">
                <el-input v-model="queryParams.model" placeholder="请输入型号" clearable
                          @keyup.enter.native="handleQuery"/>
            </el-form-item>
            <el-form-item label="规格" prop="rule">
                <el-input v-model="queryParams.rule" placeholder="请输入规格" clearable
                          @keyup.enter.native="handleQuery"/>
            </el-form-item>

            <el-form-item label="单位" prop="consumeUnit">
                <el-input v-model="queryParams.consumeUnit" placeholder="请输入耗材单位" clearable
                          @keyup.enter.native="handleQuery"/>
            </el-form-item>

            <el-form-item label="厂商" prop="vender">
                <el-input v-model="queryParams.vender" placeholder="请输入厂商" clearable
                          @keyup.enter.native="handleQuery"/>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                           v-hasPermi="['basic:consumable:add']">新增
                </el-button>
            </el-col>
            <!--      <el-col :span="1.5">-->
            <!--        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['basic:consumable:edit']">修改</el-button>-->
            <!--      </el-col>-->
            <el-col :span="1.5">
                <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple"
                           @click="handleDelete" v-hasPermi="['basic:consumable:remove']">删除
                </el-button>
            </el-col>

            <el-col :span="1.5">
                <el-button type="warning" plain icon="el-icon-upload" size="mini" @click="handleImport"
                           v-hasPermi="['basic:consumable:import']">导入
                </el-button>
            </el-col>

            <el-col :span="1.5">
                <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                           v-hasPermi="['basic:consumable:export']">导出
                </el-button>
            </el-col>

            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <!-- 耗材列表 -->
        <el-table v-loading="loading" :data="consumableList" row-key="consumeId"
                  :row-class-name="getRowClassName">
            <el-table-column type="selection" width="55" align="center"/>
            <el-table-column label="唯一编号" align="center" prop="no"/>

            <el-table-column label="耗材名称" align="center" prop="name"/>

            <el-table-column label="型号" align="center" prop="model">
                <template slot-scope="scope">
                    <el-input v-if="scope.row.editing" v-model="scope.row.model" placeholder="请输入型号"></el-input>
                    <span v-else>{{ scope.row.model }}</span>
                </template>
            </el-table-column>

            <el-table-column label="规格" align="center" prop="rule">
                <template slot-scope="scope">
                    <el-input v-if="scope.row.editing" v-model="scope.row.rule" placeholder="请输入规格"></el-input>
                    <span v-else>{{ scope.row.rule }}</span>
                </template>
            </el-table-column>

            <el-table-column label="耗材类型" align="center" prop="fixedType">
                <template slot-scope="scope">
                    <dict-tag :options="dict.type.basic_consumable_type_dict" :value="scope.row.fixedType"/>
                </template>
            </el-table-column>

            <el-table-column label="单位" align="center" prop="consumeUnit">
                <template slot-scope="scope">
                    <el-input v-if="scope.row.editing" v-model="scope.row.consumeUnit"
                              placeholder="请输入单位"></el-input>
                    <span v-else>{{ scope.row.consumeUnit }}</span>
                </template>
            </el-table-column>

            <el-table-column label="厂商" align="center" prop="vender">
                <template slot-scope="scope">
                    <el-input v-if="scope.row.editing" v-model="scope.row.vender" placeholder="请输入厂商"></el-input>
                    <span v-else>{{ scope.row.vender }}</span>
                </template>
            </el-table-column>

            <el-table-column label="数量" align="center" prop="number" width="210">
                <template slot-scope="scope">
                    <el-input-number v-if="scope.row.editing" v-model="scope.row.number" :min="1"
                                     label="请输入数量"></el-input-number>
                    <span v-else>{{ scope.row.number }}</span>
                </template>
            </el-table-column>

            <el-table-column label="阈值" align="center" prop="warningNumber" width="210">
                <template slot-scope="scope">
                    <el-input-number v-if="scope.row.editing" v-model="scope.row.warningNumber" :min="1"
                                     label="请输入警戒阈值"></el-input-number>
                    <span v-else>{{ scope.row.warningNumber }}</span>
                </template>
            </el-table-column>

            <el-table-column label="保修日期" align="center" prop="warrantyDate">
                <template slot-scope="scope">
                    <el-date-picker v-if="scope.row.editing" v-model="scope.row.warrantyDate" type="date"
                                    placeholder="选择保修日期" style="width: 100%;" value-format="yyyy-MM-dd"/>
                    <span v-else-if="scope.row.warrantyDate" :class="getWarrantyClass(scope.row.warrantyDate)">
                        <span v-if="getWarrantyDays(scope.row.warrantyDate) > 0">
                            剩于 {{ getWarrantyDays(scope.row.warrantyDate) }} 天
                        </span>
                        <span v-else>
                            已过期 {{ Math.abs(getWarrantyDays(scope.row.warrantyDate)) }} 天
                        </span>
                    </span>
                    <span v-else>-</span>
                </template>
            </el-table-column>

            <el-table-column label="最近一次入库" align="center" prop="storageDate"/>

            <el-table-column label="状态" align="center" prop="status">
                <template slot-scope="scope">
                    <el-select v-if="scope.row.editing" v-model="scope.row.status" placeholder="请选择状态" style="width: 100%;">
                        <el-option v-for="dict in dict.type.basic_consumable_status_dict"
                                   :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"/>
                    </el-select>
                    <dict-tag v-else :options="dict.type.basic_consumable_status_dict" :value="scope.row.status"/>
                </template>
            </el-table-column>

            <el-table-column label="备注" align="center" prop="remark">
                <template slot-scope="scope">
                    <el-input v-if="scope.row.editing" v-model="scope.row.remark" placeholder="请输入备注"></el-input>
                    <span v-else>{{ scope.row.remark }}</span>
                </template>
            </el-table-column>

            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200px">
                <template slot-scope="scope">
                    <template v-if="scope.row.editing">
                        <!-- 编辑状态：显示保存和取消按钮 -->
                        <el-button type="primary" plain @click="handleSave(scope.row)"
                                   v-hasPermi="['basic:consumable:edit']">
                            保存
                        </el-button>
                        <el-button type="warning" plain @click="handleCancel(scope.row)"
                                   v-hasPermi="['basic:consumable:edit']">
                            取消
                        </el-button>
                    </template>
                    <template v-else>
                        <!-- 正常状态：显示编辑和删除按钮 -->
                        <el-button type="warning" plain @click="handleUpdate(scope.row)"
                                   v-hasPermi="['basic:consumable:edit']">
                            修改
                        </el-button>
                        <el-button type="danger" plain @click="handleDelete(scope.row)"
                                   v-hasPermi="['basic:consumable:remove']">
                            删除
                        </el-button>
                    </template>

                    <template>
                        <el-button type="warning" plain @click="handleApply(scope.row)" v-hasPermi="['basic:consumable:apply']">
                            申请
                        </el-button>
                    </template>
                </template>
            </el-table-column>


        </el-table>

        <!-- 固定资产导入对话框 -->
        <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
            <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
                       :action="upload.url + '?updateSupport=' + upload.updateSupport"
                       :disabled="upload.isUploading" :on-progress="handleFileUploadProgress"
                       :on-success="handleFileSuccess" :auto-upload="false" drag>
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <div class="el-upload__tip text-center" slot="tip">
                    <span>仅允许导入xls、xlsx格式文件。</span>
                    <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                             @click="importTemplate">下载模板
                    </el-link>
                </div>
            </el-upload>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitFileForm">确 定</el-button>
                <el-button @click="upload.open = false">取 消</el-button>
            </div>
        </el-dialog>

        <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                    @pagination="getList"/>

        <!-- 新增耗材对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="80px">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="商品编号" prop="no">
                            <el-input v-model="form.no" placeholder="请输入商品编号"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="耗材名称" prop="name">
                            <el-input v-model="form.name" placeholder="请输入耗材名称"/>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="12">
                        <el-form-item label="型号" prop="model">
                            <el-input v-model="form.model" placeholder="请输入型号"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="规格" prop="rule">
                            <el-input v-model="form.rule" placeholder="请输入规格"/>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="12">
                        <el-form-item label="单位" prop="consumeUnit">
                            <el-input v-model="form.consumeUnit" placeholder="请输入单位"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="厂商" prop="vender">
                            <el-input v-model="form.vender" placeholder="请输入厂商"/>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="12">
                        <el-form-item label="数量" prop="number">
                            <el-input-number v-model="form.number" :min="1" placeholder="请输入数量"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="警戒阈值" prop="warningNumber">
                            <el-input-number v-model="form.warningNumber" :min="1" placeholder="请输入警戒阈值"/>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="12">
                        <el-form-item label="保修日期" prop="warrantyDate">
                            <el-date-picker v-model="form.warrantyDate" type="date" placeholder="选择保修日期"
                                            style="width: 100%;" value-format="yyyy-MM-dd"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="耗材类型" prop="fixedType">
                            <el-select v-model="form.fixedType" placeholder="请选择耗材类型" style="width: 100%;">
                                <el-option v-for="dict in dict.type.basic_consumable_type_dict"
                                           :key="dict.value" :label="dict.label" :value="dict.value"/>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="12">
                        <el-form-item label="状态" prop="status">
                            <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%;">
                                <el-option v-for="dict in dict.type.basic_consumable_status_dict"
                                           :key="dict.value" :label="dict.label" :value="dict.value"/>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <!-- 预留位置或者添加其他需要的字段 -->
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="24">
                        <el-form-item label="备注" prop="remark">
                            <el-input v-model="form.remark" placeholder="请输入备注" type="textarea" :rows="3"/>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>

        <!-- 耗材申请对话框 -->
        <el-dialog :title="applyDialog.title" :visible.sync="applyDialog.open" width="500px" append-to-body>
            <el-form ref="applyForm" :model="applyForm" :rules="applyRules" label-width="80px">

                <el-form-item label="耗材名称" prop="consumableName">
                    <el-input v-model="applyForm.consumableName" :disabled="true"/>
                </el-form-item>

                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="申请数量" prop="applyNumber">
                      <el-input-number v-model="applyForm.applyNumber" :min="1" :max="applyForm.availableNumber"
                                       placeholder="请输入申请数量" style="width: 100%;"/>
                      <div style="color: #909399; font-size: 12px; margin-top: 5px;">
                        可申请数量：{{ applyForm.availableNumber }} {{ applyForm.consumeUnit || '个' }}
                      </div>
                    </el-form-item>
                  </el-col>

                  <el-col :span="12">
                  </el-col>
                </el-row>


                <el-form-item label="申请用途" prop="purpose">
                    <el-select v-model="applyForm.purpose" placeholder="请选择或输入申请用途" style="width: 100%;"
                               filterable allow-create default-first-option>
                        <el-option label="考试使用" value="考试使用"/>
                        <el-option label="教学演示" value="教学演示"/>
                        <el-option label="实验操作" value="实验操作"/>
                        <el-option label="设备维护" value="设备维护"/>
                        <el-option label="其他用途" value="其他用途"/>
                    </el-select>
                </el-form-item>



                <el-form-item label="备注说明" prop="remark">
                    <el-input v-model="applyForm.remark" placeholder="请输入备注说明" type="textarea" :rows="3"/>
                </el-form-item>
            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitApply">提 交</el-button>
                <el-button @click="cancelApply">取 消</el-button>
            </div>
        </el-dialog>

    </div>
</template>

<script>
import {
    listConsumable,
    getConsumable,
    delConsumable,
    addConsumable,
    updateConsumable,
    listConsumableE, addConsumableApply
} from "@/api/basic/consumable";
import {copyObj} from "@/utils/zzDouUtils/objUtil";
import {getToken} from "@/utils/auth";

export default {
    name: "Consumable",
    dicts: ['basic_asset_type_dict','basic_consumable_type_dict', 'basic_asset_status_dict' ,'basic_consumable_status_dict'],
    data() {
        return {
            // 遮罩层
            loading: false,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 资产耗材表格数据
            consumableList: [],
            // 资产耗材预警数据
            consumableListE: [],
            // 学生导入参数
            upload: {
                // 是否显示弹出层（资产导入）
                open: false,
                // 弹出层标题（资产导入）
                title: "",
                // 是否禁用上传
                isUploading: false,
                // 是否更新已经存在的资产数据
                updateSupport: 0,
                // 设置上传的请求头部
                headers: {Authorization: "Bearer " + getToken()},
                // 上传的地址
                url: process.env.VUE_APP_BASE_API + "/basic/consumable/importData"
            },
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 申请对话框参数
            applyDialog: {
                open: false,
                title: "耗材申请"
            },
            // 申请表单数据
            applyForm: {
                consumableId: null,
                consumableName: '',
                consumeUnit: '',
                availableNumber: 0,
                applyNumber: 1,
                purpose: '',
                applicant: '',
                applyDate: '',
                remark: ''
            },
            // 申请表单验证规则
            applyRules: {
                applyNumber: [
                    { required: true, message: "申请数量不能为空", trigger: "blur" },
                    { type: 'number', min: 1, message: "申请数量至少为1", trigger: "blur" }
                ],
                purpose: [
                    { required: true, message: "申请用途不能为空", trigger: ["change", "blur"] }
                ],
                applyDate: [
                    { required: true, message: "申请时间不能为空", trigger: "change" }
                ]
            },
            // 编辑状态缓存
            editCache: {},
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                name: null,
                no: null,
                model: null,
                rule: null,
                price: null,
                fixedType: null,
                consumeUnit: null,
                type: null,
                status: null,
                vender: null,
                serviceTel: null,
                venderTel: null,
                warrantyDate: null,
                number: null,
                warningNumber: null,
                factoryDate: null,
                storageDate: null,
                storagePlace: null,
                nowPlace: null,
                charge: null,
                borrower: null,
            },
            // 表单参数
            form: {},
            // 表单校验
            rules: {
                no: [
                    { required: true, message: '商品编号不能为空', trigger: 'blur' }
                ],
                name: [
                    { required: true, message: '耗材名称不能为空', trigger: 'blur' }
                ],
                number: [
                    { required: true, message: '数量不能为空', trigger: 'change' }
                ],
                warningNumber: [
                    { required: true, message: '警戒阈值不能为空', trigger: 'change' }
                ],
                warrantyDate: [
                    { required: true, message: '保修日期不能为空', trigger: 'change' },
                    { type: 'date', required: true, message: '请选择保修日期', trigger: 'change' }
                ],
                fixedType: [
                    { required: true, message: '耗材类型不能为空', trigger: 'change' }
                ],
                status: [
                    { required: true, message: '状态不能为空', trigger: 'change' }
                ]
            }
        };
    },
    created() {
        this.getListE();
        this.getList();
    },
    methods: {
        // 获取资产耗材（库存预警信息）
        getListE(){
            listConsumableE().then(response => {
                this.consumableListE = response.data;

                // 数据加载完成后检查库存预警（管理员角色）
                this.checkInventoryAlert1();
            });
        },
        /** 查询资产耗材列表 */
        getList() {
            this.loading = true;
            listConsumable(this.queryParams).then(response => {
                // 为每个数据行添加编辑状态标识和预警标记
                this.consumableList = response.rows.map(row => {
                    return {...row, editing: false};
                });
                this.total = response.total;
                this.loading = false;

                // 数据加载完成后检查库存预警并设置行颜色标记
                this.checkInventoryAlert();
            });
        },

        /** 检查用户是否为管理员 */
        isAdmin() {
            const roles = this.$store.getters.roles || [];
            // 检查是否包含admin角色（假设管理员角色标识为'admin'）
            return roles.includes('admin') || roles.includes('ADMIN');
        },
        /** 检查库存预警并显示弹窗 - 用于getList方法中的列表行颜色标记 */
        checkInventoryAlert() {
            // 为列表数据添加预警标识，用于行背景色显示
            this.consumableList.forEach(item => {
                const number = parseInt(item.number) || 0;
                const warningNumber = parseInt(item.warningNumber) || 0;

                // 红色预警：库存数量 < 预警数量 × 50%
                if (number < warningNumber * 0.5 && warningNumber > 0) {
                    item.alertLevel = 'red';
                }
                // 黄色预警：预警数量 × 50% ≤ 库存数量 < 预警数量
                else if (number < warningNumber && warningNumber > 0) {
                    item.alertLevel = 'yellow';
                } else {
                    item.alertLevel = 'normal';
                }
            });
        },

        /** 检查库存预警并显示弹窗 - 用于getListE方法中的弹窗提醒 */
        checkInventoryAlert1() {
            // 检查是否已经是管理员
            if (!this.isAdmin()) {
                return; // 只有管理员才显示预警弹窗
            }

            // 数据为空时不显示弹窗
            if (!this.consumableListE || this.consumableListE.length === 0) {
                return;
            }

            // 构建预警信息（数据已经是筛选过的红色预警数据）
            let alertMessage = `耗材库存预警提醒\n\n`;
            alertMessage += `🔴 严重不足 (${this.consumableListE.length}项)\n\n`;

            this.consumableListE.forEach(item => {
                alertMessage += `• ${item.name} (编号: ${item.no}) - 库存: ${item.number}, 阈值: ${item.warningNumber}\n`;
            });

            alertMessage += `\n请及时补充库存！`;

            // 使用Element UI对话框显示美观的弹窗
            const message = this.consumableListE.map(item =>
                `• ${item.name} (编号: ${item.no}) - 库存: ${item.number}, 阈值: ${item.warningNumber}`
            ).join('<br>');

            this.$alert(
                `<div style="text-align: left; line-height: 1.8;">
                    <div style="font-weight: bold; margin-bottom: 12px; font-size: 16px;">
                        🔴 严重不足 (${this.consumableListE.length}项)
                    </div>
                    <div style=" padding: 12px; border-radius: 4px; border-left: 4px solid #f56c6c;">
                        ${message}
                    </div>
                    <div style="color: #606266; font-weight: bold; margin-top: 15px; text-align: center;">
                        请及时补充库存！
                    </div>
                </div>`,
                '耗材库存预警提醒',
                {
                    dangerouslyUseHTMLString: true,
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    showCancelButton: false,
                    type: 'warning',
                    center: true,
                    customClass: 'consumable-alert-dialog'
                }
            );
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                id: null,
                name: null,
                no: null,
                model: null,
                rule: null,
                price: null,
                fixedType: null,
                consumeUnit: null,
                type: null,
                status: null,
                vender: null,
                serviceTel: null,
                venderTel: null,
                warrantyDate: null,
                number: null,
                warningNumber: null,
                factoryDate: null,
                storageDate: null,
                storagePlace: null,
                nowPlace: null,
                charge: null,
                borrower: null,
                remark: null,
                deleted: null,
                createTime: null
            };
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.id)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.open = true;
            this.title = "新增耗材";
        },
        /** 内联编辑模式 - 开始修改 */
        handleUpdate(row) {
            this.startEdit(row.id);
        },
        /** 内联编辑模式 - 取消修改 */
        handleCancel(row) {
            this.cancelEdit(row.id);
        },
        /** 内联编辑模式 - 保存修改 */
        handleSave(row) {
            // 验证必填字段
            if (!row.name) {
                this.$message.warning('请输入耗材名称');
                return;
            }

            // 调用后端更新接口
            updateConsumable(row).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.finishEdit(row.id);
                this.getList();
            }).catch(error => {
                this.$modal.msgError("修改失败：" + (error.message || '未知错误'));
            });
        },
        /** 开始编辑模式 */
        startEdit(id) {
            const row = this.consumableList.find(item => item.id === id);
            if (row && !row.editing) {
                // 保存原始数据到缓存
                this.editCache[id] = copyObj(row);
                // 设置编辑状态
                row.editing = true;
                // 强制更新表格
                this.$set(this.consumableList, this.consumableList.indexOf(row), row);
            }
        },
        /** 取消编辑模式 */
        cancelEdit(id) {
            const row = this.consumableList.find(item => item.id === id);
            if (row && row.editing) {
                // 从缓存恢复原始数据
                if (this.editCache[id]) {
                    Object.assign(row, this.editCache[id]);
                    delete this.editCache[id];
                }
                row.editing = false;
                // 强制更新表格
                this.$set(this.consumableList, this.consumableList.indexOf(row), row);
            }
        },
        /** 完成编辑模式 */
        finishEdit(id) {
            const row = this.consumableList.find(item => item.id === id);
            if (row && row.editing) {
                // 清除缓存
                delete this.editCache[id];
                row.editing = false;
                // 强制更新表格
                this.$set(this.consumableList, this.consumableList.indexOf(row), row);
            }
        },
        /** 修改按钮操作 */
        handleUpdate_old(row) {
            this.reset();
            this.form = copyObj(row);
            this.open = true;
            this.title = "修改资产耗材";
        },
        /** 提交按钮 */
        submitForm() {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    // 格式化保修日期为yyyy-MM-dd格式
                    if (this.form.warrantyDate && typeof this.form.warrantyDate === 'object') {
                        this.form.warrantyDate = this.formatDate(this.form.warrantyDate);
                    }

                    if (this.form.id != null) {
                        updateConsumable(this.form).then(response => {
                            this.$modal.msgSuccess("修改成功");
                            this.open = false;
                            this.getList();
                        });
                    } else {
                        addConsumable(this.form).then(response => {
                            this.$modal.msgSuccess("新增成功");
                            this.open = false;
                            this.getList();
                        });
                    }
                }
            });
        },

        /** 日期格式化方法 */
        formatDate(date) {
            if (!date) return '';
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            return `${year}-${month}-${day}`;
        },

        // 计算距离保修日期的天数
        getWarrantyDays(warrantyDateStr) {
            if (!warrantyDateStr) return 0;

            const today = new Date();
            today.setHours(0, 0, 0, 0); // 设置为当天开始时间

            const warrantyDate = new Date(warrantyDateStr);
            warrantyDate.setHours(0, 0, 0, 0); // 设置为保修日期开始时间

            const diffTime = warrantyDate.getTime() - today.getTime();
            const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));

            return diffDays;
        },

        /** 获取保修日期的CSS类 */
        getWarrantyClass(warrantyDateStr) {
          const days = this.getWarrantyDays(warrantyDateStr);
          if (days <= 30) {
            return 'warranty-expiring-soon'; // 深红色背景
          } else if (days > 30 && days <= 45) {
            return 'warranty-expiring-warning'; // 黄色背景
          }
          return ''; // 默认无特殊样式
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const ids = row.id || this.ids;
            this.$modal.confirm('是否确认删除资产耗材编号为"' + row.name + '"的数据项？').then(function () {
                return delConsumable(ids);
            }).then(() => {
                this.getList();
                this.$modal.msgSuccess("删除成功");
            }).catch(() => {
            });
        },

        /** 申请按钮操作 */
        handleApply(row) {
            this.applyDialog.title = `耗材申请 - ${row.name}`;
            this.applyForm.consumableId = row.id;
            this.applyForm.consumableName = row.name;
            this.applyForm.consumeUnit = row.consumeUnit || '个';
            this.applyForm.availableNumber = row.number;
            this.applyForm.applyNumber = 1;
            this.applyForm.purpose = '';
            // 设置申请人为当前用户（如果可以获取的话）
            this.applyForm.applicant = '';
            this.applyForm.phone = '';
            this.applyForm.remark = '';
            this.applyDialog.open = true;
        },

        /** 提交申请 */
        submitApply() {
            this.$refs.applyForm.validate((valid) => {
                if (valid) {
                    // 检查申请数量是否超过可用数量
                    if (this.applyForm.applyNumber > this.applyForm.availableNumber) {
                        this.$message.error('申请数量不能超过可用数量');
                        return;
                    }
                    // 这里应该调用API提交申请
                    addConsumableApply(this.applyForm).then(response => {
                        this.$modal.msgSuccess("申请提交成功，等待审批");
                        this.applyDialog.open = false;
                        this.getList();
                        // 重置表单
                        this.resetApplyForm();
                    });
                }
            });
        },

        /** 取消申请 */
        cancelApply() {
            this.applyDialog.open = false;
            this.resetApplyForm();
        },

        /** 重置申请表单 */
        resetApplyForm() {
            this.applyForm = {
                consumableId: null,
                consumableName: '',
                consumeUnit: '',
                availableNumber: 0,
                applyNumber: 1,
                purpose: '',
                applicant: '',
                phone: '',
                applyDate: '',
                remark: ''
            };
            if (this.$refs.applyForm) {
                this.$refs.applyForm.resetFields();
            }
        },

        /** 格式化日期时间 */
        formatDateTime(date) {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            const seconds = String(date.getSeconds()).padStart(2, '0');
            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        },

        /** 根据库存数量设置行背景色 */
        getRowClassName({row, rowIndex}) {
            // 使用checkInventoryAlert方法中设置的alertLevel属性
            if (row.alertLevel === 'red') {
                return 'warning-row';
            } else if (row.alertLevel === 'yellow') {
                return 'normal-warning-row';
            }
            // 其他情况使用默认样式
            return '';
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download('basic/consumable/export', {
                ...this.queryParams
            }, `consumable_${new Date().getTime()}.xlsx`)
        },

        /** 导入按钮操作 */
        handleImport() {
            this.upload.title = "耗材导入";
            this.upload.open = true;
        },

        /** 下载模板操作 */
        importTemplate() {
            this.download('basic/consumable/importTemplate', {}, `导入耗材模板_${new Date().getTime()}.xlsx`)
        },

        // 文件上传中处理
        handleFileUploadProgress(event, file, fileList) {
            this.upload.isUploading = true;
        },

        // 提交上传文件
        submitFileForm() {
            this.$refs.upload.submit();
        },

        // 文件上传成功处理
        handleFileSuccess(response, file, fileList) {
            this.upload.open = false;
            this.upload.isUploading = false;
            this.$refs.upload.clearFiles();

            // 对导入结果进行校验
            // this.validateImportResult(response);
            // 创建一个新的对话框实例，使用更大的宽度和适当的样式
            this.$alert("<div style='overflow: auto;max-width: none; width: 1200px;max-height: 70vh;padding: 10px 20px 0;white-space: pre-wrap;word-break: break-word;'>" + response.msg + "</div>", "导入结果", {
                dangerouslyUseHTMLString: true,
                customClass: 'wide-alert',
                center: false
            });
            this.getList();
        },

        // 校验导入结果
        // validateImportResult(response) {
        //     if (!response || !response.data) {
        //         return;
        //     }
        //
        //     const validationRules = {
        //         name: { required: true, type: 'string', fieldName: '资产名称' },
        //         type: { required: true, type: 'number', fieldName: '耗材类型' },
        //         number: { required: true, type: 'number', fieldName: '数量' },
        //         status: { required: true, type: 'number', fieldName: '资产状态' },
        //         price: { required: true, type: 'number', fieldName: '单价' },
        //         manageDeptId: { required: true, type: 'number', fieldName: '管理部门' }
        //     };
        //
        //     const errors = [];
        //
        //     // 检查是否包含导入数据
        //     if (Array.isArray(response.data) && response.data.length > 0) {
        //         response.data.forEach((item, index) => {
        //             const rowNumber = index + 1; // 表格行号从1开始
        //
        //             Object.keys(validationRules).forEach(field => {
        //                 const rule = validationRules[field];
        //                 const value = item[field];
        //
        //                 // 检查是否为空
        //                 if (rule.required && (value === null || value === undefined || value === '')) {
        //                     errors.push(`第${rowNumber}行：${rule.fieldName}不能为空`);
        //                     return;
        //                 }
        //
        //                 // 如果有值，检查数据类型
        //                 if (value !== null && value !== undefined && value !== '') {
        //                     const actualType = typeof value;
        //                     if (rule.type === 'number' && isNaN(Number(value))) {
        //                         errors.push(`第${rowNumber}行：${rule.fieldName}必须是数字类型，当前值为"${value}"`);
        //                     } else if (rule.type === 'string' && actualType !== 'string') {
        //                         errors.push(`第${rowNumber}行：${rule.fieldName}必须是字符串类型`);
        //                     }
        //                 }
        //             });
        //         });
        //     }
        //
        //     // 如果有校验错误，显示错误信息
        //     if (errors.length > 0) {
        //         const errorMessage = errors.join('\n');
        //         this.$alert(errorMessage, "导入数据校验失败", {
        //             confirmButtonText: '确定',
        //             type: 'error',
        //             customClass: 'wide-alert',
        //             center: false,
        //             dangerouslyUseHTMLString: true,
        //             callback: action => {
        //                 this.getList(); // 即使校验失败也刷新列表
        //             }
        //         });
        //         console.error('导入数据校验失败:', errors);
        //     }
        // },
    }
};
</script>

<style>
/* 为导入结果弹窗添加宽样式 */
.wide-alert {
    width: 700px !important;
    max-width: none !important;
}
.wide-alert .el-message-box__content {
    padding: 20px;
}

/* 耗材库存预警弹窗样式 */
.consumable-alert-dialog {
    position: fixed !important;
    top: 50% !important;
    left: 50% !important;
    transform: translate(-50%, -50%) !important;
    margin: 0 !important;
    max-width: 500px !important;
    width: 90% !important;
    border-radius: 8px !important;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15) !important;
}
.consumable-alert-dialog .el-message-box__content {
    padding: 20px 20px 10px 20px !important;
}
.consumable-alert-dialog .el-message-box__header {
    background: #fef0f0 !important;
    border-bottom: 1px solid #fbc4c4 !important;
    padding: 15px 20px !important;
    border-radius: 8px 8px 0 0 !important;
}
.consumable-alert-dialog .el-message-box__title {
    color: #f56c6c !important;
    font-weight: bold !important;
    font-size: 16px !important;
}
.consumable-alert-dialog .el-message-box__headerbtn .el-message-box__close {
    color: #f56c6c !important;
    font-size: 18px !important;
    font-weight: bold !important;
}
.consumable-alert-dialog .el-message-box__btns {
    text-align: center !important;
    padding: 15px 20px !important;
    background: #fafafa !important;
    border-radius: 0 0 8px 8px !important;
}
.consumable-alert-dialog .el-button--primary {
    background: #f56c6c !important;
    border-color: #f56c6c !important;
    padding: 10px 25px !important;
    border-radius: 4px !important;
}
.consumable-alert-dialog .el-button--primary:hover {
    background: #f78989 !important;
    border-color: #f78989 !important;
}

/* 库存预警行背景色样式 */
.el-table .warning-row {
    background-color: #ffebee !important; /* 浅红色背景 */
}

.el-table .warning-row > td {
    background-color: #ffebee !important;
}

.el-table .normal-warning-row {
    background-color: #fff8e1 !important; /* 浅黄色背景 */
}

.el-table .normal-warning-row > td {
    background-color: #fff8e1 !important;
}

/* 确保背景色在hover时也保持 */
.el-table tr.warning-row:hover > td {
    background-color: #ffcdd2 !important; /* 悬停时的红色 */
}

.el-table tr.normal-warning-row:hover > td {
    background-color: #ffecb3 !important; /* 悬停时的黄色 */
}
/* 保修日期预警样式 */
.warranty-expiring-warning {
  background-color: #fff8e1;
  padding: 4px 8px;
  border-radius: 4px;
  color: #ff9800;
  font-weight: bold;
}

.warranty-expiring-soon {
  background-color: #ffebee;
  padding: 4px 8px;
  border-radius: 4px;
  color: #f44336;
  font-weight: bold;
}

.warranty-text {
  font-size: 26px; /* Increased from default 12px to 14px (2px larger) */
}

</style>
